﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace laohan.Common.Common
{
    public partial class API
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="workingDirectory"></param>
        /// <param name="fileName"></param>
        /// <param name="args"></param>
        public static void StartProcess(string workingDirectory, string fileName, string args = "")
        {
            try
            {
                RunProcess(workingDirectory, fileName, args);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format(@"启动进程{0}发生错误，错误原因：{1}", fileName, ex.Message));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="workingDirectory"></param>
        /// <param name="fileName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static Process RunProcess(string workingDirectory, string fileName, string args = "")
        {
            try
            {
                var info = new ProcessStartInfo();

                info.FileName = fileName;//设置外部程序名
                info.Arguments = args;//设置外部程序的启动参数
                info.WorkingDirectory = workingDirectory;//设置外部程序名
                info.UseShellExecute = true;

                return Process.Start(info);
            }
            catch (Exception ex)
            {

                throw new Exception(string.Format(@"启动进程{0}发生错误，错误原因：{1}", fileName, ex.Message));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fullfileName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static Process RunProcess(string fullfileName, string args = "")
        {
            var path = Path.GetDirectoryName(fullfileName);
            var fileName = Path.GetFileName(fullfileName);

            return RunProcess(path, fileName, args);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        public static void ExplorerOpen(string fileName)
        {
            Process p = new Process();

            p.StartInfo.FileName = "explorer.exe";
            p.StartInfo.Arguments = string.Format(@" /select, {0}", fileName);
            p.Start();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static FileExtension CheckFileType(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);

            string fileType = string.Empty;

            try
            {
                byte data = br.ReadByte();

                fileType += data.ToString();

                data = br.ReadByte();

                fileType += data.ToString();

                FileExtension extension;
                try
                {
                    extension = (FileExtension)Enum.Parse(typeof(FileExtension), fileType);
                }
                catch
                {
                    extension = FileExtension.VALIDFILE;
                }

                return extension;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    br.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string ByteArrayToString(byte[] bytes, Encoding encoding)
        {
            if (encoding == null)
            {
                encoding = Encoding.Default;
            }

            return encoding.GetString(bytes);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static byte[] StringToByteArray(string str, Encoding encoding)
        {
            byte[] bytes;

            try
            {
                bytes = encoding.GetBytes(str);
            }
            catch (Exception ex)
            {
                throw new Exception("string类型字符串转换成byte[]发生错误-->" + ex.Message);
            }

            return bytes;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteArrayToString(byte[] bytes)
        {
            return ByteArrayToString(bytes, null);
        }

        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static byte[] GetFileBytes(string filePath)
        {
            byte[] result;

            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                try
                {
                    BinaryReader binaryReader = new BinaryReader(fileStream);
                    result = binaryReader.ReadBytes((int)fileStream.Length);
                    binaryReader.Close();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetFileToString(string filePath, Encoding encoding)
        {
            var bytes = GetFileBytes(filePath);

            return ByteArrayToString(bytes, encoding);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public static string GetFileToString(string filePath)
        {
            return GetFileToString(filePath, Encoding.Default);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileFullName"></param>
        public static void CreateFile(string fileFullName, string content)
        {
            try
            {
                FileInfo file = new FileInfo(fileFullName);

                if (!File.Exists(fileFullName))
                {
                    using (var sw = file.CreateText())
                    {
                        sw.Write(content);
                        sw.Close();
                    }
                }
                else
                {
                    using (var sw = file.AppendText())
                    {
                        sw.Write(content);
                        sw.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("创建文件error:" + ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        public static void CreateFile(string fileName, byte[] bytes)
        {
            try
            {
                var path = Path.GetDirectoryName(fileName);

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                MemoryStream memoryStream = new MemoryStream(bytes);
                FileStream fileStream = new FileStream(fileName, FileMode.Create);

                memoryStream.WriteTo(fileStream);
                memoryStream.Close();
                fileStream.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format(@"写文件{0}发生错误，错误原因：{1}", fileName, ex.Message));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="newFilePath"></param>
        public static void FileRename(string filePath, string newFilePath)
        {
            File.Move(filePath, newFilePath);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string SelectFile()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*)|*.*"; //设置要选择的文件的类型

            var file = string.Empty;

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                file = fileDialog.FileName;//返回文件的完整路径                
            }

            return file;
        }

        /// <summary>
        /// 
        /// </summary>
        public static string GetImg()
        {
            var fileDialog = new OpenFileDialog();

            fileDialog.Filter = "图像文件(JPeg, Gif, Bmp, etc.) | *.jpg; *.jpeg; *.gif; *.bmp; *.tif; *.tiff; *.png; | JPeg 图像文件(*.jpg; *.jpeg)"
                        + "|*.jpg;*.jpeg |GIF 图像文件(*.gif)|*.gif |BMP图像文件(*.bmp)|*.bmp|Tiff图像文件(*.tif;*.tiff)|*.tif;*.tiff|Png图像文件(*.png)"
                        + "| *.png |所有文件(*.*)|*.*";

            string fileName = string.Empty;

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                fileName = fileDialog.FileName;
            }

            return fileName;
        }
    }
}